/*********************************************************************************
 *      Copyright:  (C) 2014 EAST
 *                  All rights reserved.
 *
 *       Filename:  recv.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/29/2014)
 *         Author:  fulinux <fulinux@sina.com>
 *      ChangeLog:  1, Release initial version on "07/29/2014 08:30:29 AM"
 *                 
 ********************************************************************************/

/* recv.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>

#include "msgque.h"

static volatile int running = 1;

void sigterm(int signo)
{
    running = 0;
}

int main (int argc, char **argv)
{
    int i;
    msgque_t msgque_r;
    msgque_t msgque_w;


    /* 初始化消息队列 */
    if(-1 == msgque_init(&msgque_r, 100)){
        return -1;
    }
    printf ("msgque_r.msgid = %d\n", msgque_r.msgid);

    /* 初始化消息队列 */
    if(-1 == msgque_init(&msgque_w, 101)){
        return -1;
    }
    printf ("msgque_w.msgid = %d\n", msgque_w.msgid);

    signal(SIGTERM, sigterm);
    signal(SIGHUP, sigterm);
    signal(SIGINT, sigterm);

    msgque_setdebug(&msgque_w, 0);
    msgque_setdebug(&msgque_r, 0);
    while(running){

        /* 接收消息队列 */
        if(-1 == msgque_read(&msgque_r)){
            return -1;
        }

        printf("message mtype: %ld\n", msgque_r.msgbuf.mtype);
        printf("message mtest: ");
        for(i = 0; i < MSGSIZE; i++){
            printf ("0x%X ", msgque_r.msgbuf.mtext[i]);
            msgque_w.msgbuf.mtext[i] = 0x11;
        }
        printf ("\n\n");

        if (0 == strncmp(msgque_r.msgbuf.mtext, "end", 3))
            running = 0;

        msgque_w.msgbuf.mtype = msgque_r.msgbuf.mtype;
        if(-1 == msgque_write(&msgque_w)){
            break;
        }
        sleep(3);
    }

    /* 注销消息队列 */
    if (-1 == msgque_exit(&msgque_r)){
        return -1;
    }

    /* 注销消息队列 */
    if (-1 == msgque_exit(&msgque_w)){
        return -1;
    }

    printf ("bye!\n");

    exit(EXIT_FAILURE);
} /* ----- End of main() ----- */


